<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    @register="registerDrawer"
    @ok="handleSubmit"
    okText="保存"
    width="60%"
    :okAuth="'m8:order:flow:batchOver'"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <div style="font-size: 20px; padding: 30px">
      图纸总数：
      <span style="font-size: 26px; color: red; margin-right: 80px">{{ record.picSumQty }}张</span>
      流程数量：
      <span style="font-size: 26px; color: red">{{ record.flowCount }}</span>
    </div>
    <BasicForm @register="registerForm">
      <template #testDataChildList>
        <BasicTable
          @register="registerTestDataChildTable"
          @row-click="handleTestDataChildRowClick"
          ref="tableRef"
        />
      </template>
    </BasicForm>
    <BasicModal
      @register="register2"
      v-bind="$attrs"
      @ok="handleOk"
      :canFullscreen="false"
      okText="是"
      width="40%"
      :showCancelBtn="false"
    >
      <!-- @cancel="closeFunc"  cancelText="否"-->
      <div
        style="text-align: center; height: 200px; line-height: 200px; font-size: 60px; color: red"
      >
        是否全部完成
      </div>
      <template #centerFooter>
        <a-button :loading="loading" @click="closeFunc()">
          <Icon icon="ant-design:close-outlined" /> 否
        </a-button>
      </template>
    </BasicModal>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsOrderM8OperCheckForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { batchSave } from '/@/api/m8/order/order';
  import { BasicTable, useTable } from '/@/components/Table';
  import { officeTreeData } from '/@/api/sys/office';

  const emit = defineEmits(['success', 'register']);
  const tableRef = ref();

  const { t } = useI18n('order.m8OperCheck');
  const { showMessage } = useMessage();
  const record = ref<any>({
    picSumQty: '',
    flowCount: '',
    flowList: [],
    manCodes: {},
  });
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: '批量完工',
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: '负责人',
      field: 'manCodes',
      fieldLabel: 'manNames',
      component: 'TreeSelect',
      required: true,
      componentProps: {
        api: officeTreeData,
        params: { isLoadUser: true, userIdPrefix: '', isAll: true, isShowCode: true },
        canSelectParent: false,
        allowClear: true,
      },
    },
    {
      label: '',
      field: 'childList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'testDataChildList',
    },
  ];

  const [registerTestDataChildTable, testDataChildTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleTestDataChildDelete.bind(this, record),
          },
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    canResize: true,
    resizeHeightOffset: 80,
  });

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [register2, { openModal, setModalProps: setModalProps2, closeModal: closeModal2 }] =
    useModal();

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    record.value = data;
    record.value.__t = new Date().getTime();
    setFieldsValue({
      manCodes: record.value.manCodes.userCode,
      manNames: record.value.manCodes.userName,
    });
    setTestDataChildTableData(data);
    setDrawerProps({ loading: false });
  });

  function handleTestDataChildDelete(record: Recordable) {
    testDataChildTable.deleteTableDataRecord(record);
  }

  async function setTestDataChildTableData(_res: Recordable) {
    testDataChildTable.setColumns([
      {
        title: t('工序'),
        dataIndex: 'orderFlow.oper.operName',
        width: 130,
        align: 'left',
      },
      {
        title: t('图号'),
        dataIndex: 'orderPic.picno',
        width: 130,
        align: 'left',
      },
      {
        title: t('图名'),
        dataIndex: 'orderPic.picname',
        width: 150,
        align: 'left',
      },
      {
        title: t('完工数'),
        dataIndex: 'iqty',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
        className: 'need',
        editable: true,
      },
      {
        title: t('加工时长/分'),
        dataIndex: 'useTime',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
        className: 'need',
        editable: true,
        ifShow: false,
      },
      {
        title: t('完工说明'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
        ifShow: false,
      },
    ]);
    if (record.value.flowList) {
      record.value.flowList.forEach((item, index) => {
        if (!item.id) {
          item.id = index + 1;
        }
      });
    }
    testDataChildTable.setTableData(record.value.flowList || []);
  }

  function handleTestDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  async function getTestDataChildList() {
    let testDataChildListValid = true;
    let testDataChildList: Recordable[] = [];
    for (const record of testDataChildTable.getDataSource()) {
      // 验证控件内容，并取消行的编辑状态（如果验证失败返回false）
      if (!(await record.onEdit?.(false, true))) {
        testDataChildListValid = false;
      }
      testDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of testDataChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      testDataChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!testDataChildListValid) {
      throw { errorFields: [{ name: ['testDataChildList'] }] };
    }
    return testDataChildList;
  }

  async function handleOk() {
    handleSave('1');
  }

  async function closeFunc() {
    handleSave('0');
  }

  async function handleSubmit() {
    let flag = true;
    let data = testDataChildTable.getDataSource().map((item) => {
      if (!item.orderFlow) {
        flag = false;
        showMessage(`图纸【${item.orderPic.id}】没有可完工的工序！`);
      }
    });
    if (flag) {
      openModal(true, '');
    }
  }

  async function handleSave(boverOper) {
    try {
      const data = await validate();
      let childList = await getTestDataChildList();
      const dataList = childList
        .map((item) => {
          return {
            orderFlow: {
              id: item.orderFlow.id,
            },
            iqty: item.iqty,
            remarks: item.remarks,
          };
        })
        .filter(Boolean);
      let params = {
        manCodes: data.manCodes,
        boverOper: boverOper,
        data: JSON.stringify(dataList),
      };
      setDrawerProps({ confirmLoading: true });
      const res = await batchSave(params);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
      tableRef.value.setProps({ editable: true });
    } finally {
      setDrawerProps({ confirmLoading: false });
      setModalProps2({ confirmLoading: false });
      setTimeout(closeModal2);
    }
  }
</script>

<style lang="less" scoped>
  :deep(.need) {
    color: red;
  }

  :deep(.jeesite-editable-cell__action) {
    display: none;
  }
</style>
